﻿using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FangDuShi_API.Controllers
{
    /// <summary>
    /// 内容数据交换用API
    /// 用户内部服务器之间的交换
    /// </summary>
    public class ApiPrivateController : Controller
    {
        /// <summary>
        /// 手机验证码BLL
        /// </summary>
        private BLL.MobileCAPTCHA mobileCAPTCHABLL = new BLL.MobileCAPTCHA();

      
        private UniValidate uniValidate = new UniValidate();
        /// <summary>
        /// 地区BLL
        /// </summary>
        private BLL.District districtBLL = new BLL.District();
        /// <summary>
        /// 中介公司BLL
        /// </summary>
        private BLL.Agency agencyBLL = new BLL.Agency();
        /// <summary>
        /// 中介门店BLL
        /// </summary>
        private BLL.AgencyBranch agencyBranchBLL = new BLL.AgencyBranch();
        /// <summary>
        /// 私有API方法
        /// </summary>
        /// <param name="postData">发送数据</param>
        /// <param name="sysUser">授权用户名</param>
        /// <param name="sysPwd">授权用户密码</param>
        /// <returns></returns>
        public string ApiPrivateMethod(string postData)
        {
            string returnMsg = "";

            JObject msgJson = JObject.Parse(postData);
            //if (msgJson["sysUser"]!=null && msgJson["sysPwd"]!=null)


            string sysUser = msgJson["sysUser"] == null ? "" : msgJson["sysUser"].ToString();
            string sysPwd = msgJson["sysPwd"] == null ? "" : msgJson["sysPwd"].ToString();
            if (sysPwd == "admin" && sysPwd == "admin")
            {

                string method = msgJson["method"] == null ? "" : msgJson["method"].ToString();
                string msg = msgJson["msg"] == null ? "" : msgJson["msg"].ToString();

                switch (method)
                {
                    case "RealtorRegSave":
                        {
                            returnMsg = RealtorRegSave();
                            break;
                        }
                    case "GetMobileCAPTCHA":
                        {
                            //获取手机验证码
                            msgJson = JObject.Parse(msg);
                            string mobileNo = msgJson["mobileNo"].ToString();
                            string ipAddress = msgJson["ipAddress"].ToString();

                            returnMsg=GetMobileCAPTCHA(mobileNo, ipAddress);
                            break;
                        }
                    case "GetProvinceList":
                        {
                            returnMsg = GetProvinceList();
                            break;
                        }
                    case "GetCityList":
                        {

                            break;
                        }
                    case "GetAgencyList":
                        {
                            msgJson = JObject.Parse(msg);

                            string districtNo = msgJson["districtNo"].ToString();
                            returnMsg = GetAgencyList(districtNo);
                            break;
                        }
                    case "GetAgencyBranchList":
                        {
                            msgJson = JObject.Parse(msg);

                            string agencyID = msgJson["agencyID"].ToString();
                            decimal tmpDecimal = 0;
                            if (decimal.TryParse(agencyID, out tmpDecimal))
                            {
                                returnMsg = GetAgencyBranchList(tmpDecimal);
                            }
                            else
                            {
                                returnMsg = uniValidate.ParamError();
                            }
                          
                            break;
                        }
                    default:
                        {
                            returnMsg = uniValidate.UnsupportedOpenApi();
                            break;
                        }
                }
            }
            else
            {
                returnMsg = uniValidate.UserIsNotAuthorized();
            }

            return returnMsg;


        }
        private string GetAgencyBranchList(decimal agencyID)
        {
            string returnMsg = "";
            List<Model.AgencyBranch> agencyBranchList = agencyBranchBLL.GetAgencyBranchList(agencyID);
            List<JObject> jObjectList = new List<JObject>();
            foreach (Model.AgencyBranch tmpModel in agencyBranchList)
            {
                JObject jObject = new JObject();
                jObject["id"] = tmpModel.FAgencyBranchID;
                jObject["name"] = tmpModel.FBranchBriefName;
                jObjectList.Add(jObject);
            }

            string msg = JsonConvert.SerializeObject(jObjectList);
            returnMsg = uniValidate.NoError(msg);

            return returnMsg;
        }

        /// <summary>
        /// 获取中介公司
        /// </summary>
        /// <returns></returns>
        private string GetAgencyList(string districtNo)
        {
            string returnMsg = "";
            List<Model.Agency> agencyList = agencyBLL.GetList(districtNo);
            List<JObject> jObjectList = new List<JObject>();
            foreach (Model.Agency tmpModel in agencyList)
            {
                JObject jObject = new JObject();
                jObject["id"] = tmpModel.FAgencyID;
                jObject["name"] = tmpModel.FAgencyBriefName;
                jObjectList.Add(jObject);
            }

            string msg = JsonConvert.SerializeObject(jObjectList);
            returnMsg = uniValidate.NoError(msg);

            return returnMsg;
        }
        /// <summary>
        /// 获取省
        /// </summary>
        /// <returns></returns>
        private string GetProvinceList()
        {
            string returnMsg = "";
            List<Model.District> provinceList = districtBLL.GetProvinceList();

            List<JObject> jObjectList = new List<JObject>();

            foreach(Model.District tmpModel in provinceList)
            {
                JObject jObject = new JObject();
                if (tmpModel.FDistrictNo.Length == 2)
                {
                    tmpModel.FDistrictNo=tmpModel.FDistrictNo + "0000";
                }
                else
                {
                    if (tmpModel.FDistrictNo.Length == 4)
                    {
                        tmpModel.FDistrictNo = tmpModel.FDistrictNo + "00";
                    }
                }
                jObject["FDistrictNo"] = tmpModel.FDistrictNo;
                jObject["FDistrictName"] = tmpModel.FDistrictName;
                jObjectList.Add(jObject);

            }
            string msg = JsonConvert.SerializeObject(jObjectList);
            returnMsg = uniValidate.NoError(msg);

            return returnMsg;
        }
        /// <summary>
        /// 获取手机验证码
        /// </summary>
        /// <param name="mobileNo"></param>
        /// <returns></returns>
        private string GetMobileCAPTCHA(string mobileNo,string ipAddress)
        {
            string returnMsg = "";

            string errMsg = "";
            int interval=120;
            int ipCount=20;
            int mobileCount=3;

            bool canSend = mobileCAPTCHABLL.CheckCanSendCAPTCHA(mobileNo, interval, ipCount, mobileCount,ipAddress,out errMsg);
            if (canSend)
            {
                Model.MobileCAPTCHA mobileCAPTCHAModel = new Model.MobileCAPTCHA();

                string captcha = Common.GenerateUtil.GetRandomNumber(6);

                mobileCAPTCHAModel.FCAPTCHA = captcha;
                mobileCAPTCHAModel.FCAPTCHACls = "001";
                mobileCAPTCHAModel.FGenIP = ipAddress;
                mobileCAPTCHAModel.FIsUse = "N";
                mobileCAPTCHAModel.FMobile = mobileNo;

                try
                {
                    mobileCAPTCHABLL.Add(mobileCAPTCHAModel, 30);
                    returnMsg = uniValidate.NoError();
                }
                catch
                {
                    returnMsg = uniValidate.ServerInternalError();
                }

            }
            else
            {
                returnMsg = uniValidate.GetMobileCAPTCHAError(errMsg);
            }
            return returnMsg;
        }
       
        /// <summary>
        /// 经纪人注册保存
        /// </summary>
        /// <returns></returns>
        private string RealtorRegSave()
        {
            string returnMsg = "";
            //string logid = OperateSession.get(GlobalConstant.PARAM_REALTOR_ID);
            //if (string.IsNullOrEmpty(logid))
            //{
            //    returnMsg = uniValidate.UserIsNotLogin();
            //}
            //else
            //{
            //    JObject jObject = new JObject();
            //    jObject["ServerDatetime"] = apiBLL.GetServerDatetime().ToString("yyyy-MM-dd HH:mm:ss");
            //    returnMsg = uniValidate.NoError(jObject.ToString());
            //}
            return returnMsg;
        }

        public string FileUpload()
        {
            Stream st = Request.InputStream;
            long ll = st.Length;
            // object obj = Request.Form["profile_picture"];
            for (int i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFileBase upload = Request.Files[i];
                string aa = Request.Files.GetKey(i);
                //if (upload.ContentLength>0 )
                upload.SaveAs(Server.MapPath("/Content/" + Guid.NewGuid() + ".jpg"));
            //    foreach (var key in ChatHub.ChatConnection.Keys)
            //    {

            //        foreach (string clientId in ChatHub.ChatConnection.GetConnections(key).ToList())
            //        {
            //            GlobalHost.ConnectionManager.GetHubContext<ChatHub>().Clients.Client(clientId).addNewMessageToPage("", "{'type':'voice','message':'55.amr'}}");

            //        }

            //    }
            }
            string message = "{'type':'msg','message':'file success'}";
            return message;





            //GlobalHost.ConnectionManager.GetHubContext<ChatHub>().Clients.


        }
        [ValidateInput(false)]
        public string FileUpload2()
        {
            this.ValidateRequest = false;
            Stream st = Request.InputStream;
            long ll = st.Length;
            object obj = Request.Form["profile_picture"];

            object picUrl = Request.Form["picUrl"];
            object title = Request.Form["title"];
            for (int i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFileBase upload = Request.Files[i];
                string aa = Request.Files.GetKey(i);
                //if (upload.ContentLength>0 )
                upload.SaveAs(Server.MapPath("/Content/" + Guid.NewGuid() + ".jpg"));
                //foreach (var key in ChatHub.ChatConnection.Keys)
                //{

                //    foreach (string clientId in ChatHub.ChatConnection.GetConnections(key).ToList())
                //    {
                //        GlobalHost.ConnectionManager.GetHubContext<ChatHub>().Clients.Client(clientId).addNewMessageToPage("", "{'type':'voice','message':'55.amr'}}");

                //    }

                //}
            }
            string message = "{'type':'msg','message':'file success'}";
            return message;





            //GlobalHost.ConnectionManager.GetHubContext<ChatHub>().Clients.


        }
	}
}